package br.com.petshop.dao.frames;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Sidney
 */
public class MyTableModel extends DefaultTableModel {
    
    private final List entityToList;
    private final Class entityClassToList;
    private List<Method> fieldToData = new LinkedList<Method>();
    private final JTable tableToControl;
    
    public MyTableModel(Class entityClassToList, List entity,JTable tableToControl) throws IllegalAccessException, NoSuchMethodException {
        super();
        this.entityToList = entity;
        this.entityClassToList = entityClassToList;
        this.tableToControl = tableToControl;
        startAddColumns();
        startAddValues();
    }
    
    private void startAddColumns() throws NoSuchMethodException {
        //aqui tenho a referência a classe.
        for (Field field : entityClassToList.getDeclaredFields()) {
            SwingColumn theAnotation = field.getAnnotation(SwingColumn.class);
            if (theAnotation != null) {//coluna deve ser adicionada, pois tem a anotação
                addColumn(field.getName());
                String methodName = "get" + field.getName().toUpperCase().charAt(0) + field.getName().substring(1);
                fieldToData.add(entityClassToList.getDeclaredMethod(methodName, null));
            }
        }
    }

    private void startAddValues() throws IllegalAccessException, IllegalArgumentException {
        
        for (Object entity : entityToList) {
            List<Object> valuesToAdd = new LinkedList<Object>();
            
            for (Method method : fieldToData) {
                try {
                    valuesToAdd.add(method.invoke(entity));
                } catch (InvocationTargetException ex) {
                    Logger.getLogger(MyTableModel.class.getName()).log(Level.SEVERE, null, ex);
                }
                
            }
            addRow(valuesToAdd.toArray());
        }
    }
}
